<template>
  <div style="height: 100%; display: flex">
    <div class="titlebar">
      <div class="title">某海洋水文环境保障教学支持系统</div>
    </div>
    <LayerManage :viewerHandle="viewer" />
    <div id="cesiumContainer" style="height: 100%; width: 100%"></div>
    <Timeline />
    <RightTools :viewerHandle="viewer" />
    <div v-if="isLoading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <div class="loading-text">数据加载中...</div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, ref, onBeforeUnmount, watch } from "vue";
import CesiumNavigation from "cesium-navigation-es6";
import LayerManage from "./LayerManage.vue";
import RightTools from "./RightTools.vue";
import Timeline from "./TimeLine.vue"; // 引入 Timeline 组件
import * as Cesium from "cesium";
import { useNeiboStore } from "@/stores/neiboStore";
import { useEddyStore } from "@/stores/eddyStore";
import { useYuecengStore } from "@/stores/yuecengStore";
import { useCurrentStore } from "@/stores/currentStore";
import { useWenyanStore } from "@/stores/wenyanStore";
import { useFengmianStore } from "@/stores/fengmianStore";
import { useData2DStore } from "@/stores/data2DStore";
import { useStationsStore } from "@/stores/stationsStore";
import { useScaleStore } from "@/stores/scaleStore";
import { format } from "date-fns";
import { getYanDuPouMianData, getYanDuPouMianDataByPoint } from "@/api";
import duanmianDialog from "@/utils/clickopen/duanmianDialog";
import ProfileDialog from "@/utils/clickopen/profileDialog";
import eventBus from "@/utils/eventBus";
const stationsStore = useStationsStore();
const fengmianStore = useFengmianStore();
const wenyanStore = useWenyanStore();
const currentStore = useCurrentStore();
const yuecengStore = useYuecengStore();
const eddyStore = useEddyStore();
const neiboStore = useNeiboStore();
const data2DStore = useData2DStore();
const isLoading = ref(false);
let viewer = ref(null);
let sectionHandler = null;
let sectionStartPoint = null;
let sectionEndPoint = null;
let tempLineEntity = null;
let startPointEntity = null;
let endPointEntity = null;
let instructionLabel = null;
let type = ref("templature");
onMounted(async () => {
  const apiUrl = window.appConfig;
  console.log(apiUrl);
  Cesium.Ion.defaultAccessToken =
    "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkZmI0MDA3MS01NzlhLTQ3YTktYjE5My0xNDMzMTg3NzBmYmUiLCJpZCI6MTEzNTQ5LCJpYXQiOjE2Njc0NjgxMjR9.1dFxU1juvQN2XvnbtFHyaUw-za1hYVrP0cAn5xXajvs";
  viewer.value = new Cesium.Viewer("cesiumContainer", {
    requestWebgl1: true, //设置使用Webgl1
    animation: true, //动画小部件
    shouldAnimate: true,
    baseLayerPicker: false, //地图图层组件
    fullscreenButton: false, //全屏组件
    geocoder: false, //地理编码搜索组件
    homeButton: false, //首页组件
    infoBox: false, //信息框
    sceneModePicker: false, //场景模式
    selectionIndicator: false, //选取指示器组件
    timeline: true, //时间轴
    navigationHelpButton: false, //帮助按钮
    navigationInstructionsInitiallyVisible: false,
    baseLayerPicker: false, // 禁用默认底图
    // 加载地形函数，提供高分辨率的全球 3D 地形数据
    // terrainProvider: await Cesium.createWorldTerrainAsync({
    //   // 提高地形表面的光照和阴影效果的精度
    //   requestVertexNormals: true,
    //   // 水体呈现流动效果
    //   requestWaterMask: false,
    //   terrainExaggeration: 3.0, // 设置地形夸张系数
    // }),
  });
  viewer.value = viewer.value;
  viewer.value.scene.screenSpaceCameraController.zoomFactor = 1; //相机缩放速率
  // viewer.value.scene.globe.depthTestAgainstTerrain = true; // 确保地形深度检测
  // viewer.value.scene.primitives.depthTestAgainstTerrain = true; // 确保原始图元深度检测
  var imageryProvider = new Cesium.WebMapTileServiceImageryProvider({
    url: "https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/WMTS",
    layer: "World_Imagery",
    style: "default",
    format: "image/jpeg",
    tileMatrixSetID: "GoogleMapsCompatible",
    maximumLevel: 8,
    credit: new Cesium.Credit("© Esri", "https://www.esri.com/"),
  });
  // var imageryProvider = new Cesium.UrlTemplateImageryProvider({
  //   url: apiUrl,
  //   minimumLevel: 0,
  //   maximumLevel: 10, // 或 GeographicTilingScheme
  //   credit: new Cesium.Credit("Local Tiles"),
  // });
  const options = {
    // 罗盘
    enableCompass: true,
    // 缩放控件
    enableZoomControls: false,
    // 距离图例
    enableDistanceLegend: false,
    // 指南针外环
    enableCompassOuterRing: true,
  };

  new CesiumNavigation(viewer.value, options);
  viewer.value.camera.setView({
    destination: {
      x: -3558397.3075464107,
      y: 7300150.323537398,
      z: 2041719.4055434903,
    },
    orientation: {
      heading: 6.27669114823209,
      pitch: -1.248789382616426,
      roll: 6.283120764297309,
    },
  });
  viewer.value.imageryLayers.addImageryProvider(imageryProvider);
  viewer.value.cesiumWidget.creditContainer.style.display = "none";
  viewer.value.timeline.container.style.display = "none"; // 隐藏时间线
  viewer.value.animation.container.style.visibility = "hidden"; // 隐藏动画控件
  // viewer.value.scene.debugShowFramesPerSecond = true; //帧数显示
  console.log(Cesium.VERSION, "cesium版本号");

  viewer.value.scene.screenSpaceCameraController.minimumZoomDistance = 500000; //相机的高度的最小值
  viewer.value.scene.screenSpaceCameraController.maximumZoomDistance = 5000000;
  eddyStore.setViewer(viewer);
  yuecengStore.setViewer(viewer);
  currentStore.setViewer(viewer);
  wenyanStore.setViewer(viewer);
  neiboStore.setViewer(viewer);
  fengmianStore.setViewer(viewer);
  data2DStore.setViewer(viewer);
  stationsStore.setViewer(viewer);
  viewer.value.camera.changed.addEventListener(() => {});
  // 添加断面选择事件监听
  eventBus.$on("toggle-section-selection", (isActive) => {
    if (isActive.isSelectingSection) {
      type.value = isActive.type == 1 ? "templature" : "salinity";
      startSectionSelection();
    } else {
      cancelSectionSelection(isActive.type);
    }
  });
  eventBus.$on("toggle-profile-selection", (isActive) => {
    if (isActive.isSelectingProfile) {
      type.value = isActive.type == 1 ? "templature" : "salinity";
      startProfileSelection();
    } else {
      cancelProfileSelection();
    }
  });
});
function startSectionSelection() {
  // 清除之前的绘制
  clearSectionDrawing();

  // 创建提示标签
  createInstructionLabel("请选择起点");

  // 设置鼠标事件
  setupSectionHandlers();
}

function createInstructionLabel(text) {
  if (instructionLabel) {
    viewer.value.entities.remove(instructionLabel);
  }

  instructionLabel = viewer.value.entities.add({
    label: {
      text: text,
      font: "14pt sans-serif",
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      outlineWidth: 2,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(0, -20),
      fillColor: Cesium.Color.WHITE,
      outlineColor: Cesium.Color.BLACK,
      showBackground: true,
      backgroundColor: new Cesium.Color(0.165, 0.165, 0.165, 0.7),
      backgroundPadding: new Cesium.Cartesian2(10, 5),
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
    },
  });
}

function setupSectionHandlers() {
  // 移除现有处理器
  if (sectionHandler) {
    sectionHandler.destroy();
  }

  sectionHandler = new Cesium.ScreenSpaceEventHandler(
    viewer.value.scene.canvas
  );

  // 鼠标移动事件
  sectionHandler.setInputAction((movement) => {
    const scaleStore = useScaleStore();
    const scale = scaleStore.currentScale || 1;
    // 反向计算坐标
    const adjustedPosition = new Cesium.Cartesian2(
      movement.endPosition.x / scale,
      movement.endPosition.y / scale
    );
    const ray = viewer.value.camera.getPickRay(adjustedPosition);
    const position = viewer.value.scene.globe.pick(ray, viewer.value.scene);

    if (!position) return;

    // 更新标签位置
    instructionLabel.position = position;

    if (sectionStartPoint) {
      // 已经选择了起点，绘制临时线
      drawTempLine(position);
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  // 鼠标点击事件
  sectionHandler.setInputAction((click) => {
    const scaleStore = useScaleStore();
    const scale = scaleStore.currentScale || 1;
    // 反向计算坐标
    const adjustedPosition = new Cesium.Cartesian2(
      click.position.x / scale,
      click.position.y / scale
    );
    const ray = viewer.value.camera.getPickRay(adjustedPosition);
    const position = viewer.value.scene.globe.pick(ray, viewer.value.scene);

    if (!position) return;

    const cartographic = Cesium.Cartographic.fromCartesian(position);
    const longitude = Cesium.Math.toDegrees(cartographic.longitude);
    const latitude = Cesium.Math.toDegrees(cartographic.latitude);

    if (!sectionStartPoint) {
      // 选择起点
      sectionStartPoint = { longitude, latitude, position };
      drawStartPoint(position);
      instructionLabel.label.text = "请选择终点";
    } else {
      // 选择终点
      sectionEndPoint = { longitude, latitude, position };
      drawEndPoint(position);
      completeSectionDrawing();
    }
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}

function drawStartPoint(position) {
  startPointEntity = viewer.value.entities.add({
    position: position,
    point: {
      pixelSize: 10,
      color: Cesium.Color.RED,
      outlineColor: Cesium.Color.WHITE,
      outlineWidth: 2,
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      zIndex: 9999, // 确保在最上层
    },
  });
}

function drawEndPoint(position) {
  endPointEntity = viewer.value.entities.add({
    position: position,
    point: {
      pixelSize: 10,
      color: Cesium.Color.BLUE,
      outlineColor: Cesium.Color.WHITE,
      outlineWidth: 2,
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      zIndex: 9999, // 确保在最上层
    },
  });
}

function drawTempLine(endPosition) {
  // 移除临时线
  if (tempLineEntity) {
    viewer.value.entities.remove(tempLineEntity);
  }

  // 创建新的临时线
  tempLineEntity = viewer.value.entities.add({
    polyline: {
      positions: [sectionStartPoint.position, endPosition],
      width: 2,
      material: new Cesium.PolylineDashMaterialProperty({
        color: Cesium.Color.YELLOW,
        dashLength: 16,
      }),
      clampToGround: true,
    },
  });
}
async function completeSectionDrawing() {
  isLoading.value = true; // 开始加载

  // 创建最终线段
  const sectionLine = viewer.value.entities.add({
    polyline: {
      positions: [sectionStartPoint.position, sectionEndPoint.position],
      width: 3,
      material: Cesium.Color.GREEN,
      clampToGround: true,
      zIndex: 9998,
    },
  });

  try {
    await sendSectionToBackend(
      sectionStartPoint,
      sectionEndPoint,
      sectionLine,
      startPointEntity,
      endPointEntity
    );
  } catch (error) {
    console.error("断面请求失败:", error);
    // 失败时清除已创建的实体
    [sectionLine, startPointEntity, endPointEntity].forEach((entity) => {
      if (entity) viewer.value.entities.remove(entity);
    });
  } finally {
    isLoading.value = false; // 结束加载
    cleanupDrawingResources();
  }
}

async function sendSectionToBackend(
  startPoint,
  endPoint,
  sectionLine,
  startPointEntity,
  endPointEntity
) {
  let newtype = type.value == "templature" ? 1 : 2;
  let newname = type.value == "templature" ? "温度断面" : "盐度断面";
  let prarms = {
    ctime:
      format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss", {
        timeZone: "UTC",
      }) || "2025-03-19",
    pointA: {
      latitude: startPoint.latitude,
      longitude: startPoint.longitude,
    },
    pointB: {
      latitude: endPoint.latitude,
      longitude: endPoint.longitude,
    },
    type: newtype,
  };

  let res = await getYanDuPouMianData(prarms);
  try {
    let dialog = new duanmianDialog({
      viewer: viewer.value,
      title: newname,
      gridData: res,
      dataType: newtype,
      roadPath: [startPoint, endPoint],
      sectionLine: sectionLine,
      startPoint: startPointEntity,
      endPoint: endPointEntity,
    });
  } catch (error) {
    console.error("创建剖面弹窗失败:", error);
    // 如果失败，清除所有已创建的实体
    [sectionLine, startPointEntity, endPointEntity].forEach((entity) => {
      if (entity) viewer.value.entities.remove(entity);
    });
  }
}

function cleanupDrawingResources() {
  // 移除临时线和标签
  if (tempLineEntity) {
    viewer.value.entities.remove(tempLineEntity);
    tempLineEntity = null;
  }

  if (instructionLabel) {
    viewer.value.entities.remove(instructionLabel);
    instructionLabel = null;
  }

  // 移除事件处理器
  if (sectionHandler) {
    sectionHandler.destroy();
    sectionHandler = null;
  }
}

function clearSectionDrawing() {
  // 清除所有绘制的实体
  if (startPointEntity) {
    viewer.value.entities.remove(startPointEntity);
    startPointEntity = null;
  }

  if (endPointEntity) {
    viewer.value.entities.remove(endPointEntity);
    endPointEntity = null;
  }

  sectionStartPoint = null;
  sectionEndPoint = null;
  cleanupDrawingResources();
}

function cancelSectionSelection() {
  clearSectionDrawing();
  eventBus.$emit("section-selection-cancelled");
}
let profileHandler = null;
let profilePoint = null;
let profilePointEntity = null;
let profileInstructionLabel = null;
// 添加剖面选择功能
function startProfileSelection() {
  clearProfileDrawing();
  createProfileInstructionLabel("请选择剖面点");
  setupProfileHandlers();
}

function createProfileInstructionLabel(text) {
  if (profileInstructionLabel) {
    viewer.value.entities.remove(profileInstructionLabel);
  }

  profileInstructionLabel = viewer.value.entities.add({
    label: {
      text: text,
      font: "14pt sans-serif",
      style: Cesium.LabelStyle.FILL_AND_OUTLINE,
      outlineWidth: 2,
      verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
      pixelOffset: new Cesium.Cartesian2(0, -20),
      fillColor: Cesium.Color.WHITE,
      outlineColor: Cesium.Color.BLACK,
      showBackground: true,
      backgroundColor: new Cesium.Color(0.165, 0.165, 0.165, 0.7),
      backgroundPadding: new Cesium.Cartesian2(10, 5),
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
    },
  });
}

function setupProfileHandlers() {
  if (profileHandler) {
    profileHandler.destroy();
  }

  profileHandler = new Cesium.ScreenSpaceEventHandler(
    viewer.value.scene.canvas
  );

  // 鼠标移动事件
  profileHandler.setInputAction((movement) => {
    const scaleStore = useScaleStore();
    const scale = scaleStore.currentScale || 1;
    const adjustedPosition = new Cesium.Cartesian2(
      movement.endPosition.x / scale,
      movement.endPosition.y / scale
    );
    const ray = viewer.value.camera.getPickRay(adjustedPosition);
    const position = viewer.value.scene.globe.pick(ray, viewer.value.scene);

    if (!position) return;

    profileInstructionLabel.position = position;
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  // 鼠标点击事件
  profileHandler.setInputAction((click) => {
    const scaleStore = useScaleStore();
    const scale = scaleStore.currentScale || 1;
    const adjustedPosition = new Cesium.Cartesian2(
      click.position.x / scale,
      click.position.y / scale
    );
    const ray = viewer.value.camera.getPickRay(adjustedPosition);
    const position = viewer.value.scene.globe.pick(ray, viewer.value.scene);

    if (!position) return;

    const cartographic = Cesium.Cartographic.fromCartesian(position);
    const longitude = Cesium.Math.toDegrees(cartographic.longitude);
    const latitude = Cesium.Math.toDegrees(cartographic.latitude);

    profilePoint = { longitude, latitude, position };
    drawProfilePoint(position);
    completeProfileSelection();
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}

function drawProfilePoint(position) {
  profilePointEntity = viewer.value.entities.add({
    position: position,
    point: {
      pixelSize: 10,
      color: Cesium.Color.RED,
      outlineColor: Cesium.Color.WHITE,
      outlineWidth: 2,
      disableDepthTestDistance: Number.POSITIVE_INFINITY,
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
      zIndex: 9999,
    },
  });
}

// 修改completeProfileSelection函数
async function completeProfileSelection() {
  isLoading.value = true; // 开始加载

  try {
    await sendProfileToBackend(profilePoint);
  } catch (error) {
    console.error("剖面请求失败:", error);
    if (profilePointEntity) {
      viewer.value.entities.remove(profilePointEntity);
      profilePointEntity = null;
    }
  } finally {
    isLoading.value = false; // 结束加载
    cleanupProfileResources();
  }
}

async function sendProfileToBackend(point) {
  try {
    let newtype = type.value == "templature" ? 1 : 2;
    let newname = type.value == "templature" ? "温度垂直剖面" : "盐度垂直剖面";
    const params = {
      ctime:
        format(eventBus.selectedDate, "yyyy-MM-dd'T'HH:mm:ss", {
          timeZone: "UTC",
        }) || "2025-03-19",
      pointA: {
        latitude: point.latitude,
        longitude: point.longitude,
      },
      type: newtype, // 使用当前图层类型
    };

    // 这里调用API获取剖面数据
    const res = await getYanDuPouMianDataByPoint(params);

    // 创建剖面弹窗
    let dialog = new ProfileDialog({
      viewer: viewer.value,
      title: newname,
      gridData: res,
      point: point,
      pointEntity: profilePointEntity,
      dataType: newtype,
    });
  } catch (error) {
    console.error("创建剖面失败:", error);
    if (profilePointEntity) {
      viewer.value.entities.remove(profilePointEntity);
      profilePointEntity = null;
    }
  }
}

function cleanupProfileResources() {
  if (profileInstructionLabel) {
    viewer.value.entities.remove(profileInstructionLabel);
    profileInstructionLabel = null;
  }

  if (profileHandler) {
    profileHandler.destroy();
    profileHandler = null;
  }
}

function clearProfileDrawing() {
  if (profilePointEntity) {
    viewer.value.entities.remove(profilePointEntity);
    profilePointEntity = null;
  }
  profilePoint = null;
  cleanupProfileResources();
}

function cancelProfileSelection() {
  clearProfileDrawing();
  eventBus.$emit("profile-selection-cancelled");
}
onBeforeUnmount(() => {
  // 清理事件监听
  eventBus.$off("toggle-section-selection");

  // 清理断面绘制资源
  cancelSectionSelection();
  eventBus.$off("toggle-profile-selection");
  cancelProfileSelection();
});
</script>
<style scoped>
.titlebar {
  position: absolute;
  top: 50px;
  width: 100%;
  z-index: 999;
  pointer-events: none;
}
.title {
  display: flex;
  text-align: center;
  justify-content: center;
  font-size: 23px;
  color: #fff; /* 字体颜色改为白色 */
  font-weight: 500;
  text-shadow: -1px -1px 0 #f00, /* 左上黑色描边 */ 1px -1px 0 #000,
    /* 右上黑色描边 */ -1px 1px 0 #f00, /* 左下黑色描边 */ 1px 1px 0 #f00,
    /* 右下黑色描边 */ 2px 2px 5px rgba(0, 0, 0, 0.7); /* 阴影 */
}
:deep(.compass) {
  left: 16%;
}
:deep(.compass-outer-ring) {
  fill: #fff;
}
:deep(.compass-outer-ring-background) {
  border: 12px solid #05415d;
}
:deep(.compass-gyro-background) {
  border: 1px solid #fff;
  background-color: #05415d;
}

:deep(.navigation-controls) {
  left: 360px;
  background-color: #05415d;
}
.slider-demo-block {
  max-width: 600px;
  display: flex;
  align-items: center;
}
.slider-demo-block .el-slider {
  margin-top: 0;
  margin-left: 12px;
}
.slider-demo-block .demonstration {
  font-size: 14px;
  color: var(--el-text-color-secondary);
  line-height: 44px;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 0;
}
.slider-demo-block .demonstration + .el-slider {
  flex: 0 0 70%;
}
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 10000;
}

.loading-spinner {
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top: 4px solid #fff;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

.loading-text {
  color: white;
  margin-top: 10px;
  font-size: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
</style>
